package com.dolphin.business.manager;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.dolphin.business.common.utils.PagerModel;
import com.dolphin.business.common.utils.SystemContext;
import com.dolphin.business.exception.BaseException;

public abstract class AbstractManager extends HibernateDaoSupport {

	public PagerModel searchPaginate(String hql) {
		return searchPaginate(hql, null);
	}

	public PagerModel searchPaginate(String hql, Object value) {
		return searchPaginate(hql, new Object[] { value });
	}

	public PagerModel searchPaginate(String hql, Object[] values) {
		return searchPaginate(hql, values, SystemContext.getOffset(),
				SystemContext.getPagesize());
	}

	public PagerModel searchPaginate(String hql, int offset, int pagesize) {
		return searchPaginate(hql, null, offset, pagesize);
	}

	public PagerModel searchPaginate(String hql, Object value, int offset,
			int pagesize) {
		return searchPaginate(hql, new Object[] { value }, offset, pagesize);
	}

	/**
	 * 分页逻辑
	 * 
	 * @param hql
	 *            如:"select o from Organization o where o.parent.id = " +
	 *            parentId
	 * @param values
	 *            所有占位符所需要的参数,做为对象数组传递
	 * @param offset
	 * @param pagesize
	 * @return
	 */
	public PagerModel searchPaginate(String hql, Object[] values, int offset,
			int pagesize) {
		PagerModel pager = new PagerModel();
		String countQueryString = getCountQueryString(hql);
		Query query = getSession().createQuery(countQueryString);
		if (values != null && values.length > 0) {
			for (int i = 0; i < values.length; i++) {
				query.setParameter(i, values[i]);
			}
		}
		// int total = 0;
		// try {
		// total = ((Long)query.uniqueResult()).intValue();
		// } catch(Exception e) {
		//
		// }
		int total = ((Long) query.uniqueResult()).intValue();
		pager.setTotal(total);

		query = getSession().createQuery(hql);
		query.setFirstResult(offset);
		query.setMaxResults(pagesize);
		if (values != null && values.length > 0) {
			for (int i = 0; i < values.length; i++) {
				query.setParameter(i, values[i]);
			}
		}
		pager.setDatas(query.list());
		return pager;
	}

	/**
	 * 得到查询总记录数的hql语句
	 * 
	 * @param hql
	 *            如: select count(*) from Organization o where o.parent.id = " +
	 *            parentId
	 * @return
	 */
	private String getCountQueryString(String hql) {
		int index = -1;
		if (hql.indexOf("from") != -1) {
			index = hql.indexOf("from");
		} else if (hql.indexOf("FROM") != -1) {
			index = hql.indexOf("FROM");
		}

		if (index != -1) {
			String queryString = hql.substring(index);
			return "select count(*) " + queryString;
		}
		throw new BaseException("非法的hql【" + hql + "】");
	}
}
